<template>
    <div class="content">
        <div class="left">
            <img src="@/assets/img2.png" class="people p-animtion" alt="people">
            <img src="@/assets/img1.png" class="sphere s-animtion" alt="sphere">
        </div>
        <div class="right">
            <div class="top">
                <div class="top-item" >
                    <span class="top-text">Home</span>
                </div>
                <div class="top-item" @click="onRegister">
                    <span class="top-text">{{isRegisterMode ?  "Login" : "Register"}}</span>
                </div>
                <div class="top-item">
                    <span class="top-text">Contact Us</span>
                </div>
                <div class="top-item">
                    <span class="top-text">Help</span>
                </div>
            </div>
            <div class="form-wrappepr">
                <h1>{{ isRegisterMode ? "Register" : "Login"}}</h1>
                <input type="text" class="inputs user" placeholder="Enter Email Or Number" v-model="loginForm.username">
                <input type="password" class="inputs pwd" placeholder="Password" v-model="loginForm.password">
                <div class="captcha-wrapper">
                    <input type="text" class="inputs captcha"  v-model="loginForm.captcha">
                    <img :src="captchaImage" class="captcha-img" alt="点击获取验证码" @click="onRefreshCaptcha">
                </div>
                <span class="tips">Recovery Password</span>
                <button type="submit" @click="onSubmit">{{ isRegisterMode ? "Sign Up" :"Sign In" }}</button>
                <div class="other-login">
                    <div class="divider">
                        <span class="line"></span>
                        <span class="divider-text">or continue with</span>
                        <span class="line"></span>
                    </div>
                    <div class="other-login-wrapper">
                        <div class="other-login-item">
                            <img src="@/assets/QQ.png" alt="QQ">
                        </div>
                        <div class="other-login-item" @click="onToggleWeChatQRCode">
                            <img src="@/assets/WeChat.png" alt="WeChat">
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
  </template>
  
<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import router from '@/router'
import { onMounted, ref, watch } from 'vue'
import {useLayoutStore} from '@/store/modules/layout'
import {showElMessage} from '@/utils/tools'

const layoutStore = useLayoutStore()

const captchaImage = ref("")
const qrcodeImage = ref({
    image: "",
    imageURL: "",
    ticket: "",
})
const isRegisterMode = ref(false)
// login 表单
const loginForm = ref({
    username: "123",
    password: "123",
    captcha: "", // 验证码字符串
    captchaKey: "", // key
})

onMounted(() => {
    getCaptcha()
})
    
// 拉取验证码
const getCaptcha = () => {
    layoutStore.getCaptchaImage()
        .then((res) => {
            if (res && res.data) {
                captchaImage.value = res.data.image
                loginForm.value.captchaKey = res.data.key
            } 
        })
        .catch(() => {})
}

const onRefreshCaptcha = () => {
    getCaptcha()
}

const onRegister = () => {
    isRegisterMode.value = !isRegisterMode.value
    reset()
}

const reset = () => {
    getCaptcha()
    Object.keys(loginForm.value).forEach(key => {
        loginForm.value[key] = ""
    })
}

const onSubmit = async() => {
    if (isRegisterMode.value) {
        layoutStore.register({
            mobile: loginForm.value.username,
            passwd: loginForm.value.password,
            key: loginForm.value.captchaKey,
            code: loginForm.value.captcha
        })
            .then((res) => {
                if (res && res.code === 200) {
                    showElMessage("注册成功", 'success', true)
                    isRegisterMode.value = !isRegisterMode.value
                }
            })
            .catch(() => {})
    } else {
        layoutStore.login({
            mobile: loginForm.value.username,
            passwd: loginForm.value.password,
            key: loginForm.value.captchaKey,
            code: loginForm.value.captcha
        })
            .then(() => {
                showElMessage("登录成功", 'success', true)
                router.push(layoutStore.lastRoute || '/home')
            })
            .catch(() => {})
    }
    reset()
}

// 拉取微信二维码图片
async function getQrcode() {
    try {
        const res = await layoutStore.getQrcodeImage()
        if (res.code !== 200) {
            throw new Error("拉取微信二维码失败！")
        }

        qrcodeImage.value.image = res.data.image
        qrcodeImage.value.imageURL = res.data.image_url
        qrcodeImage.value.ticket = res.data.ticket
        // 设置二维码状态
        const qrcode2IQrcode: IQrcode = {
            image: qrcodeImage.value.image,
            imageURL: qrcodeImage.value.imageURL,
            ticket: qrcodeImage.value.ticket,
        }
        layoutStore.setQrcode(qrcode2IQrcode)
    } catch(err) {
        showElMessage(err, 'error')
    }
}

async function onToggleWeChatQRCode()  {
    await getQrcode()
    router.push("/wechatqrcode")
}


// 绑定回车事件
const keydownEvent = () => {
	document.onkeydown = (e: any) => {
	    if (e.defaultPrevented) {
		    return;
	    }
	    // const body = document.getElementsByTagName('body')[0];
	    if (e.keyCode === 13 && e.target.baseURI.match("/login") ) { // && e.target === body
            onSubmit()
        }
	};
};

onMounted(() => {
    keydownEvent()
})

</script>
  
<style scoped >
  @import './style.css'
</style>
